﻿using System;
using RestSharp;
using Newtonsoft.Json.Linq;
using Ayatta.Contract.Domain;
using Ayatta.Contract.Component;

namespace Web.Base.OAuth
{
    /// <summary>
    /// 豆瓣
    /// </summary>
    internal sealed class DoubanClient : OAuthClient
    {
        public DoubanClient(OAuthConfig configuration): base(configuration)
        {
        }

        protected override SkResult<ExternalUser> Callback(IRestResponse response)
        {
            //https://www.douban.com/service/auth2/token
            var content = response.Content;
            var result = new SkResult<ExternalUser>();
            try
            {
                JToken error;
                var data = JObject.Parse(content);
                
                if (data.TryGetValue(ErrorKey, out error))
                {
                    result.Extra = content;
                    result.Message = error.Value<string>();
                    return result;
                }
                var user = new ExternalUser();

                var accessToken = data[AccessTokenKey].Value<string>();
                var expiresIn = data[ExpiresInKey].Value<int>();

                user.AccessToken = accessToken;
                user.ExpirationTime = DateTime.Now.AddSeconds(expiresIn);

                user.OpenId = data["douban_user_id"].Value<string>();
            }
            catch (Exception e)
            {
                result.Extra = content;
                result.Message = e.Message;
            }
            return result;
        }
    }
}